<?php
/* 
    Name：FastPHP
    CopyRight: Mr.Fu 2019SR0832915
*/
namespace app\base;
/*
    树型结构类
    Author:FastPHP
*/
class Tree
{
    /*
        Tree树型分类生成(Select>option式)
    */
    static public function Create_Tree_Html($array, $parent_key='pid', $name='name', $rootId=0, $level=0, $result="", $sel="")
    {
        foreach ($array as $leaf) {
            if ($leaf[$parent_key] == $rootId) {
                if ($sel==$leaf['id']) {
                    $selected=' selected="selected"';
                } else {
                    $selected='';
                }
                if ($level<=0) {
                    $result.='<option value="'.$leaf['id'].'" '.$selected.'>'.$leaf[$name] . '</option>';
                } else {
                    $result.='<option value="'.$leaf['id'].'" '.$selected.'>'.str_prefix('├',$level, '&nbsp;&nbsp;&nbsp;&nbsp;').$leaf[$name] . '</option>';                   
                }
                foreach ($array as $l) {
                    if ($l[$parent_key] == $leaf['id']) {
                        $result=self::Create_Tree_Html($array, $parent_key, $name, $leaf['id'], $level + 1, $result, $sel);
                        break;
                    }
                }
            }
        }
        return $result;
    }
    /*
        Tree树型分类生成(数组式)
     */
    static public function Create_Tree($array, $parent_key='pid', $rootId=0, $level=0, $result=array())
    {
        foreach ($array as $leaf) {
            if ($leaf[$parent_key] == $rootId) {
                $result[$leaf['id']]=$leaf;
                foreach ($array as $l) {
                    if ($l[$parent_key] == $leaf['id']) {
                        $result=self::Create_Tree($array, $parent_key, $leaf['id'], $level + 1, $result);
                        break;
                    }
                }
            }
        }
        return $result;
    }
    /**数组转树 */
    static public function array2tree($array,$pid='pid',$pk='id',$rootId = 0,$child='children')
    {
        $result = [];
        foreach($array as $index=>$item){
            if($item[$pid] == $rootId){
                unset($array[$index]);
                if(!empty($array)){
                    $childlist = self::array2tree($array,$pid,$pk,$item[$pk],$child);
                    if(!empty($childlist)){
                        $item[$child] = $childlist;
                    }
                }
                $result[]=$item;
            }
        }
        return $result;
    }
}